package com.cloudbroker.bcs.platform.dav.middle.bizservice.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.UUID;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.cloudbroker.bcs.common.configure.ConfigUtil;
import com.cloudbroker.bcs.common.entity.HSBCPSBackVO;
import com.cloudbroker.bcs.common.util.JSONUtil;
import com.cloudbroker.bcs.common.util.MD5Util;
import com.cloudbroker.bcs.common.util.StringUtil;
import com.cloudbroker.bcs.common.util.VOUtil;
import com.cloudbroker.bcs.common.util.ValueUtil;
import com.cloudbroker.bcs.common.validatioin.constants.ValidationErrorCodes;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.ClientErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.HSBCPSErrorCodes.OperateErr;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.AccessTokenType;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.ApplyStatus;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.status.CustomerStatus;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.BrokerLoginType;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.CommonType;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.CustomerType;
import com.cloudbroker.bcs.platform.dav.bizapi.constants.type.VerifySource;
import com.cloudbroker.bcs.platform.dav.bizapi.service.base.vo.PageVO;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.result.AdpageBrokerData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.result.AdpageData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.result.AdpageListResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.result.AdpageTenantData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.result.BrokerListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.adpage.result.TenantListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.LoginFormBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.SuggestionBackList;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.back.UserCountBackForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.BrokerRegForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.customer.vo.UserCountForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.gold.vo.RegisteForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.business.plugs.vo.ExtendGroupBuildDefaultForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.request.CreateAccountForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.request.EditRoomForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.request.GetChatroomAddrForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.response.ChatroomBackVo;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.response.CreateAccountBackVo;
import com.cloudbroker.bcs.platform.dav.bizapi.service.export.vo.response.GetChatroomAddrBackVo;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.OperateFansBizService;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.result.OperateBranchListData;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.result.OperateBranchListResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.result.OperateGetFansBackResult;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.vo.AdpageListOperateForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.vo.AdpageUpdateOperateParam;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.vo.BranchNoForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.vo.OperateFansBlockForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.vo.OperateFansGagForm;
import com.cloudbroker.bcs.platform.dav.bizapi.service.operate.vo.OperateGetFansForm;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.business.ExtendGroupT2BizService;
import com.cloudbroker.bcs.platform.dav.bizapi.t2service.export.YunxinT2BizService;
import com.cloudbroker.bcs.platform.dav.common.config.ConfigValues;
import com.cloudbroker.bcs.platform.dav.common.constant.SysContants;
import com.cloudbroker.bcs.platform.dav.common.constant.type.PlatformType;
import com.cloudbroker.bcs.platform.dav.middle.context.HSBCPSBizDataContext;
import com.cloudbroker.bcs.platform.dav.middle.entity.Adpage;
import com.cloudbroker.bcs.platform.dav.middle.entity.Broker;
import com.cloudbroker.bcs.platform.dav.middle.entity.BrokerCheck;
import com.cloudbroker.bcs.platform.dav.middle.entity.BrokerManager;
import com.cloudbroker.bcs.platform.dav.middle.entity.ChatRoom;
import com.cloudbroker.bcs.platform.dav.middle.entity.Customer;
import com.cloudbroker.bcs.platform.dav.middle.entity.Tenant;
import com.cloudbroker.bcs.platform.dav.middle.entity.ViewpointTag;
import com.cloudbroker.bcs.platform.dav.middle.entityexample.CustomerId;
import com.cloudbroker.bcs.platform.dav.middle.entityview.AdpageView;
import com.cloudbroker.bcs.platform.dav.middle.entityview.OperateGetFansView;
import com.cloudbroker.bcs.platform.dav.middle.entityview.SuggestionListView;
import com.cloudbroker.bcs.platform.dav.middle.extservice.gold.GoldService;
import com.cloudbroker.bcs.platform.dav.middle.model.CustomerCache;
import com.cloudbroker.bcs.platform.dav.middle.service.AdpageService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerCheckService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerManagerService;
import com.cloudbroker.bcs.platform.dav.middle.service.BrokerService;
import com.cloudbroker.bcs.platform.dav.middle.service.ChatRoomService;
import com.cloudbroker.bcs.platform.dav.middle.service.ChatTopicService;
import com.cloudbroker.bcs.platform.dav.middle.service.CustomerService;
import com.cloudbroker.bcs.platform.dav.middle.service.FeedbackService;
import com.cloudbroker.bcs.platform.dav.middle.service.PermissionService;
import com.cloudbroker.bcs.platform.dav.middle.service.QuestionService;
import com.cloudbroker.bcs.platform.dav.middle.service.TenantService;
import com.cloudbroker.bcs.platform.dav.middle.service.UpvoteWaterService;
import com.cloudbroker.bcs.platform.dav.middle.service.ValidateCodeService;
import com.cloudbroker.bcs.platform.dav.middle.service.ViewpointMsgService;
import com.cloudbroker.bcs.platform.dav.middle.service.ViewpointReplyService;
import com.cloudbroker.bcs.platform.dav.middle.service.ViewpointTagService;
import com.cloudbroker.bcs.platform.dav.middle.util.AccessTokenUtil;
import com.cloudbroker.bcs.platform.dav.middle.util.GoldTokenUtil;

/**
 * Created by wangxu13798 on 2016/8/15.
 */
@Service
public class OperateFansBizServiceImpl implements OperateFansBizService {
    @Resource
    private ValidateCodeService validateCodeService;
    
    @Resource
    private CustomerService customerService;
    
    @Resource
    private BrokerService brokerService;
    
    @Resource
    private ChatRoomService chatRoomService;
    
    @Resource
    private BrokerManagerService brokerManagerService;
    
    @Resource
    private PermissionService permissionService;
    
    @Resource
    private YunxinT2BizService yunxinT2;
    
    @Resource
    private ExtendGroupT2BizService extendGroupT2;
    
    @Resource
    private ViewpointTagService viewpointTagService;
    
    @Resource
    private TenantService tenantService;
    
    @Resource
    private BrokerCheckService brokerCheckService;
    
    @Resource
    private AdpageService adpageService;
    
    @Resource
    private ViewpointReplyService viewpointReplyService;
    
    @Resource
    private UpvoteWaterService upvoteWaterService;
    
    @Resource
    private ViewpointMsgService viewpointMsgService;
    
    @Resource
    private ChatTopicService chatTopicService;
    
    @Resource
    private QuestionService questionService;
    
    @Resource
    private FeedbackService feedbackService;
    
    @Resource
    private GoldService goldService;
    
    @Override
    public OperateGetFansBackResult funcOperateGetFans(OperateGetFansForm form) {
        OperateGetFansBackResult param = new OperateGetFansBackResult();
        List<Long> tenantIds = tenantService.getTenantIdsByBranchNo(form.getBranch_no());
        if (tenantIds == null) {
            return VOUtil.genErrorResult(OperateErr.TENANT_NOT_EXIST, OperateGetFansBackResult.class);
        }
        Integer pageNo = ValueUtil.getInt(form.getPage_no(), 1);
        Integer pageCount = ValueUtil.getInt(form.getPage_count(), ConfigValues.getRequestNum());
        String fansType = StringUtil.isBlank(form.getFans_type()) ? "1" : form.getFans_type();
        String customerName = StringUtil.isBlank(form.getCustomer_name()) ? null : form.getCustomer_name();
        String mobile = StringUtil.isBlank(form.getMobile()) ? null : form.getMobile();
        String startTime = StringUtil.isBlank(form.getRegister_start_time()) ? null : form.getRegister_start_time();
        String endTime = StringUtil.isBlank(form.getRegister_end_time()) ? null : form.getRegister_end_time();
        param.setCount(customerService.countOperateFans(fansType, customerName, mobile, startTime, endTime,
                tenantIds));
        List<OperateGetFansView> list = customerService.getOperateFansList(fansType, customerName, mobile,
                startTime, endTime, (pageNo - 1) * pageCount, pageCount, tenantIds);
        param.newDataList().addAll(list);
        return VOUtil.setSuccessResult(param);
    }
    
    @Override
    public HSBCPSBackVO funcOperateFansGag(OperateFansGagForm form) {
        HSBCPSBackVO param = new HSBCPSBackVO();
        if (StringUtil.isBlank(form.getTenant_id())) {
            return VOUtil.genErrorResultVo(OperateErr.TENANT_NOT_NULL);
        }
        customerService.changeGagStatus(form.getCustomer_id(), Long.parseLong(form.getTenant_id()),
                form.getGag_type());
        return VOUtil.setSuccessResult(param);
    }
    
    @Override
    public HSBCPSBackVO funcOperateFansBlock(OperateFansBlockForm form) {
        HSBCPSBackVO param = new HSBCPSBackVO();
        JSONArray jsonArray = JSONUtil.toJsonArray(form.getCustomer_ids());
        List<CustomerId> customerIds = new ArrayList<>();
        for (int i = 0; i < jsonArray.size(); i++) {
            CustomerId customerId = new CustomerId();
            JSONObject jsonObject = jsonArray.getJSONObject(i);
            customerId.setCustomer_id(jsonObject.getLong("customer_id"));
            customerId.setTenant_id(jsonObject.getInteger("tenant_id"));
            customerIds.add(customerId);
        }
        customerService.changeBlockStatus(customerIds, form.getBlock_type());
        return VOUtil.setSuccessResult(param);
    }
    
    public OperateGetFansBackResult funcOperateFansExport(OperateGetFansForm form) {
        OperateGetFansBackResult param = new OperateGetFansBackResult();
        List<Long> tenantIds = tenantService.getTenantIdsByBranchNo(form.getBranch_no());
        if (tenantIds == null) {
            return VOUtil.genErrorResult(OperateErr.TENANT_NOT_EXIST, OperateGetFansBackResult.class);
        }
        Integer pageNo = 1;
        Integer pageCount = 100;
        String fansType = StringUtil.isBlank(form.getFans_type()) ? "1" : form.getFans_type();
        String customerName = StringUtil.isBlank(form.getCustomer_name()) ? null : form.getCustomer_name();
        String mobile = StringUtil.isBlank(form.getMobile()) ? null : form.getMobile();
        String startTime = StringUtil.isBlank(form.getRegister_start_time()) ? null : form.getRegister_start_time();
        String endTime = StringUtil.isBlank(form.getRegister_end_time()) ? null : form.getRegister_end_time();
        List<OperateGetFansView> list = new ArrayList<>();
        while (true) {
            List<OperateGetFansView> singleList = customerService.getOperateFansList(fansType, customerName,
                    mobile, startTime, endTime, (pageNo - 1) * pageCount, pageCount, tenantIds);
            list.addAll(singleList);
            pageNo++;
            if (singleList.size() < pageCount) {
                break;
            }
        }
        param.newDataList().addAll(list);
        return VOUtil.setSuccessResult(param);
    }
    
    @Override
    public OperateBranchListResult funcGetBranchList(BranchNoForm form) {
        OperateBranchListResult param = new OperateBranchListResult();
        List<Tenant> list = tenantService.getBranchList(form.getBranch_no());
        List<OperateBranchListData> resultList = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            Tenant tenant = list.get(i);
            OperateBranchListData operateBranchListData = new OperateBranchListData();
            operateBranchListData.setBranch_name(tenant.getBranch_name());
            operateBranchListData.setBranch_no(tenant.getBranch_no());
            resultList.add(operateBranchListData);
        }
        param.setData_list(resultList);
        return param;
    }
    
    @Override
    public LoginFormBackForm funcOperateBrokerRegister(BrokerRegForm form) {
        String verify_code = form.getVerify_code();
        if (!StringUtil.isBlank(verify_code)) {
            if (!validateCodeService.checkCode(verify_code, form.getMobile(), "",
                    VerifySource.DAV_REGISTER.getVal())) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.CommonErr.VERIFY_CODE_WRONG, LoginFormBackForm.class);
            }
        }
        Integer tenantId = null;
        
        //有组织架构的投顾注册租户需要填写组织机构相关信息
        if (StringUtil.isBlank(form.getBranch_no())) {
            if (!StringUtil.isBlank(form.getTenant_id())) {
                try {
                    String tenantIdStr = form.getTenant_id();
                    tenantId = Integer.parseInt(tenantIdStr.substring(0, tenantIdStr.length() - 4));
                    String keyStart = tenantIdStr.substring(tenantIdStr.length() - 4);
                    Tenant tenant = tenantService.get(String.valueOf(tenantId));
                    if (!tenant.getTenant_key().startsWith(keyStart)) {
                        return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.TENANT_NOT_EXIST,
                                LoginFormBackForm.class);
                    }
                } catch (Exception e) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.TENANT_NOT_EXIST,
                            LoginFormBackForm.class);
                }
            } else {
                Tenant tenant = new Tenant();
                tenant.setCreate_date(new Date());
                tenant.setTenant_key(UUID.randomUUID().toString());
                tenantService.save(tenant);
                tenantId = tenant.getTenant_id();
            }
        } else {
            String branch_no = form.getBranch_no();
            String parent_branch_no = form.getParent_branch_no();
            @SuppressWarnings("unused")
            boolean managerFlag = managerJudge(form.getManager_branch_no());
            if (!StringUtil.isBlank(form.getTenant_id())) {
                try {
                    tenantId = ValueUtil.getInt(form.getTenant_id());
                    Tenant tenant = tenantService.get(form.getTenant_id());
                    if (tenant == null) {
                        return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.TENANT_NOT_EXIST,
                                LoginFormBackForm.class);
                    }
                } catch (Exception e) {
                    return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.TENANT_NOT_EXIST,
                            LoginFormBackForm.class);
                }
            } else {
                Tenant tenantBranch = tenantService.getByBranchNo(branch_no);
                if (tenantBranch == null) {
                    tenantBranch = tenantService.getByBranchNo(parent_branch_no);
                }
                
                Tenant tenant = new Tenant();
                tenant.setCreate_date(new Date());
                tenant.setTenant_key(UUID.randomUUID().toString());
                tenant.setBranch_no(branch_no);
                tenant.setBranch_name(form.getBranch_name());
                tenant.setParent_branch_no(parent_branch_no);
                if (tenantBranch == null) {
                    /* if (managerFlag) {
                         tenant.setBranch_grade("1");
                     } else {
                         tenant.setBranch_grade("2");
                     }*/
                    tenant.setBranch_grade("1");
                } else {
                    tenant.setBranch_grade(tenantBranch.getBranch_grade());
                }
                tenantService.save(tenant);
                tenantId = tenant.getTenant_id();
            }
        }
        
        String broker_name = StringUtil.isEmpty(form.getBroker_name()) ? form.getApplicant_name() : form
                .getBroker_name();
        if (checkUserName(broker_name)) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.USER_NAME_EXSIT, LoginFormBackForm.class);
        }
        BrokerManager brokerManager = brokerManagerService.getByMobile(form.getMobile());
        if (brokerManager != null) {
            return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.MOBILE_REGISTERED, LoginFormBackForm.class);
        }
        Broker broker = new Broker();
        //设置基础信息
        broker.setWx_account(form.getWx_account());
        broker.setBusiness_licence(form.getBusiness_licence());
        broker.setCertificate_type(form.getCertificate_type());
        broker.setCertificate_id(form.getCertificate_id());
        broker.setOwn_organ(form.getOwn_organ());
        broker.setJob_title(form.getJob_title());
        broker.setProvince_name(form.getProvince_name());
        broker.setCity_name(form.getCity_name());
        broker.setSpeciality(form.getSpeciality());
        broker.setProfile(form.getProfile());
        broker.setFr_code(form.getFr_code());
        
        broker.setEmail(form.getEmail());
        broker.setMobile(form.getMobile());
        broker.setBroker_name(broker_name);
        broker.setBroker_status(String.valueOf(CustomerStatus.NOMAL.getVal()));
        String pwd = MD5Util.encrypt(form.getPassword());
        broker.setPassword(pwd);
        broker.setWx_public_account(form.getWx_public_account());
        broker.setBroker_key(UUID.randomUUID().toString());
        
        broker.setCreate_date(new Date());
        broker.setApplicant_name(form.getApplicant_name());
        broker.setCompany(form.getCompany_name());
        broker.setAccount_holder(form.getAccount_holder());
        broker.setBank_account(form.getBank_account());
        broker.setBank_name(form.getBank_name());
        broker.setFans_num(StringUtil.isEmpty(form.getFans_num()) ? null : Integer.valueOf(form.getFans_num()));
        broker.setId_card_img_back(form.getIdcard_img_back());
        broker.setId_card_img_front(form.getIdcard_img_front());
        broker.setId_no(form.getId_no());
        broker.setWeibo_id(form.getWeibo_id());
        broker.setReply_status(String.valueOf(ApplyStatus.UNDER_REVIEW.getVal()));
        
        broker.setTenant_id(tenantId);
        brokerService.save(broker);
        
        //有组织架构的投顾注册需要审核
        if (!StringUtil.isBlank(form.getBranch_no())) {
            BrokerCheck brokerCheck = new BrokerCheck();
            brokerCheck.setBroker_id(broker.getBroker_id());
            brokerCheck.setCheck_manager(1);
            brokerCheck.setCheck_result("0");
            brokerCheck.setTenant_id(tenantId);
            brokerCheckService.save(brokerCheck);
        }
        
        BrokerManager manager = new BrokerManager();
        manager.setName(broker.getBroker_name());
        manager.setMobile(form.getMobile());
        manager.setPassword(pwd);
        manager.setBroker_flag(1);
        manager.setBroker_id(broker.getBroker_id());
        manager.setCreate_time(new Date());
        manager.setTenant_id(tenantId);
        manager.setDelete_flag(0);
        brokerManagerService.save(manager);
        
        //云信注册
        yunxinRoomReg(broker, manager, true);
        //保存默认标签
        String[] tags = ConfigValues.getDefaultViewpointTag();
        for (int i = 0; i < tags.length; i++) {
            String tagName = tags[i];
            ViewpointTag tag = new ViewpointTag();
            tag.setBroker_id(broker.getBroker_id());
            tag.setCreate_time(new Date());
            tag.setTag_name(tagName);
            tag.setTag_type(SysContants.SYSTEM_TAG_TYPE);
            tag.setOrder_num(i + 1);
            tag.setTenant_id(tenantId);
            viewpointTagService.save(tag);
        }
        
        ExtendGroupBuildDefaultForm defaultForm = new ExtendGroupBuildDefaultForm();
        defaultForm.setBroker_id(String.valueOf(broker.getBroker_id()));
        extendGroupT2.funcExtendGroupBuildDefault(defaultForm);
        LoginFormBackForm result = this.setLoginReturnForm(manager, broker, BrokerLoginType.APP);
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public BrokerListData funcOperateBrokerList(BranchNoForm form) {
        BrokerListData brokerListData = new BrokerListData();
        List<Long> tenantIds = tenantService.getTenantIdsByBranchNo(form.getBranch_no());
        List<Broker> brokerList = brokerService.getByTenants(null, tenantIds, 1, 5000);
        if (brokerList == null) {
            brokerList = new ArrayList<>();
        }
        List<AdpageBrokerData> dataList = new ArrayList<AdpageBrokerData>();
        for (Broker broker : brokerList) {
            AdpageBrokerData data = new AdpageBrokerData();
            data.setBroker_id(broker.getBroker_id());
            data.setBroker_name(broker.getBroker_name());
            dataList.add(data);
        }
        AdpageBrokerData b = new AdpageBrokerData();
        b.setBroker_id(0L);
        b.setBroker_name("默认图片");
        dataList.add(b);
        brokerListData.setData_list(dataList);
        return VOUtil.setSuccessResult(brokerListData);
    }
    
    @Override
    public TenantListData funcOperateTenantList(BranchNoForm form) {
        TenantListData tenantListData = new TenantListData();
        List<Long> tenantIDs = tenantService.getTenantIdsByBranchNo(form.getBranch_no());
        List<Tenant> tenants = tenantService.gets(tenantIDs);
        List<AdpageTenantData> adpageTenantDatas = new ArrayList<>();
        for (Tenant tenant : tenants) {
            String name = StringUtil.isEmpty(tenant.getName()) ? tenant.getBranch_name() : tenant.getName();
            /*排除无名无姓数据*/
            if (StringUtil.isEmpty(name)) {
                continue;
            }
            
            AdpageTenantData adpageTenantData = new AdpageTenantData();
            adpageTenantData.setTenant_id(String.valueOf(tenant.getTenant_id()));
            adpageTenantData.setTenant_name(name);
            adpageTenantDatas.add(adpageTenantData);
        }
        tenantListData.setData_list(adpageTenantDatas);
        return VOUtil.setSuccessResult(tenantListData);
    }
    
    @Override
    public AdpageListResult funcOperateAdpageList(AdpageListOperateForm param) {
        AdpageListResult adpageListResult = new AdpageListResult();
        List<AdpageView> adpageList = null;
        String broker_id = param.getBroker_id();
        Long brokerId = Long.valueOf(broker_id);
        String loading_img_url;
        String payStatus;
        String serviceTel;
        List<Long> tenantIDs = tenantService.getTenantIdsByBranchNo(param.getBranch_no());
        if (!brokerId.equals(0L)) {
            Broker broker = brokerService.get(broker_id);
            if (broker == null || !tenantIDs.contains(ValueUtil.getLong(broker.getTenant_id()))) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT, AdpageListResult.class);
            }
            adpageList = adpageService.getByBrokerId(brokerId, broker.getTenant_id());
            loading_img_url = broker.getLoading_img_url();
            payStatus = String.valueOf(broker.getThird_pay_status());
            serviceTel = broker.getService_tel();
        } else {
            
            Integer tenantId = Integer.valueOf(param.getTenant_id());
            Tenant tenant = tenantService.get(param.getTenant_id());
            if (tenant == null || !tenantIDs.contains(ValueUtil.getLong(tenant.getTenant_id()))) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT, AdpageListResult.class);
            }
            adpageList = adpageService.getByTenantId(tenantId);
            loading_img_url = tenant.getLoading_img_url();
            payStatus = tenant.getThird_pay_status();
            serviceTel = tenant.getService_tel();
        }
        adpageListResult.setData_list(getAdpageDataList(adpageList));
        adpageListResult.setLoading_img_url(loading_img_url);
        adpageListResult.setPay_status(payStatus);
        adpageListResult.setService_tel(serviceTel);
        return VOUtil.setSuccessResult(adpageListResult);
    }
    
    @Override
    public HSBCPSBackVO funcOperateAdpageUpdate(AdpageUpdateOperateParam param) {
        HSBCPSBackVO result = new HSBCPSBackVO();
        String broker_id = param.getBroker_id();
        Long brokerId = Long.valueOf(param.getBroker_id());
        Integer tenantId = null;
        /*broker_id 0 代表是多投顾 */
        List<Long> tenantIDs = tenantService.getTenantIdsByBranchNo(param.getBranch_no());
        if (!brokerId.equals(0L)) {
            Broker broker = brokerService.get(broker_id);
            if (broker == null || !tenantIDs.contains(ValueUtil.getLong(broker.getTenant_id()))) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT, AdpageListResult.class);
            }
            tenantId = broker.getTenant_id();
            HSBCPSBizDataContext.setTenantId(tenantId);
            /*删除旧数据*/
            adpageService.deleteByBrokerId(brokerId);
            broker.setLoading_img_url(param.getLoading_img_url());
            if (!StringUtil.isEmpty(param.getPay_status())) {
                broker.setThird_pay_status(Integer.parseInt(param.getPay_status()));
            }
            broker.setService_tel(param.getService_tel());
            brokerService.update(broker);
        } else {
            tenantId = Integer.valueOf(param.getTenant_id());
            Tenant tenant = tenantService.get(param.getTenant_id());
            if (tenant == null || !tenantIDs.contains(ValueUtil.getLong(tenant.getTenant_id()))) {
                return VOUtil.genErrorResult(HSBCPSErrorCodes.ClientErr.NO_SUCH_CLIENT, AdpageListResult.class);
            }
            /*删除旧数据*/
            adpageService.deleteByTenantId(tenantId);
            tenant.setLoading_img_url(param.getLoading_img_url());
            tenant.setThird_pay_status(param.getPay_status());
            tenant.setService_tel(param.getService_tel());
            tenantService.update(tenant);
        }
        List<Adpage> pageList = null;
        try {
            pageList = JSONObject.parseArray(param.getData_list(), Adpage.class);
        } catch (Exception e) {
            return VOUtil.genErrorResult(ValidationErrorCodes.PARAM_MALFORMED, HSBCPSBackVO.class);
        }
        
        for (Adpage adpage : pageList) {
            adpage.setBroker_id(brokerId);
            adpage.setTenant_id(tenantId);
            adpageService.save(adpage);
        }
        return VOUtil.setSuccessResult(result);
    }
    
    //检测该租户下面是否已经有昵称，有返回true,没有返回false
    private boolean checkUserName(String name) {
        Integer total = brokerManagerService.checkUserName(name) + customerService.checkUserName(name);
        if (total > 0) {
            return true;
        }
        return false;
    }
    
    /**
     * 云信注册
     * @param c
     */
    private void yunxinRoomReg(Broker c, BrokerManager manager, boolean updateDataBase) {
        yunxinReg(c, manager, updateDataBase);
        EditRoomForm param = new EditRoomForm();
        param.setCreator(manager.getYunxin_acct());
        param.setName("聊天室");
        //创建聊天室
        ChatroomBackVo room = yunxinT2.createRoom(param);
        ChatRoom cr = new ChatRoom();
        cr.setBroker_id(c.getBroker_id());
        cr.setRoom_status(CommonType.FALSE.getVal());
        cr.setYunxin_room_id(String.valueOf(room.getRoomid()));
        cr.setTenant_id(c.getTenant_id());
        chatRoomService.save(cr);
    }
    
    //检测管理平台管理员是否为云纪管理员
    private boolean managerJudge(String branchNo) {
        String[] branchSplit = branchNo.split(",");
        for (int i = 0; i < branchSplit.length; i++) {
            if (ConfigValues.getYunjiBranchNo().equals(branchSplit[i])) {
                return true;
            }
        }
        return false;
    }
    
    private LoginFormBackForm setLoginReturnForm(BrokerManager manager, Broker broker, BrokerLoginType loginType) {
        // 写会话令牌到返回结果
        LoginFormBackForm result = new LoginFormBackForm();
        result.setBroker_flag(manager.getBroker_flag());
        // 保存新的用户会话
        String access_token = saveNewBrokerSession(manager.getBroker_manager_id(), broker,
                manager.getBroker_flag() != 1, result, loginType);
        result.setUser_token(access_token);
        result.setBroker_name(broker.getBroker_name());
        result.setBroker_avatar(manager.getBroker_avatar() == null ? broker.getBroker_avatar() : manager
                .getBroker_avatar());
        result.setBroker_id(broker.getBroker_id());
        result.setYunxin_token(manager.getYunxin_token());
        result.setYunxin_acct(manager.getYunxin_acct());
        result.setBroker_key(broker.getBroker_key());
        result.setOss_prefix(ConfigValues.getInterfaceOssAddr());
        result.setManager_name(manager.getName());
        Integer roomId = chatRoomService.setYunxinRoomUrl(result, manager.getYunxin_acct(), broker.getBroker_id());
        GetChatroomAddrForm params = new GetChatroomAddrForm();
        params.setRoomid(roomId);
        params.setAccid(result.getYunxin_acct());
        GetChatroomAddrBackVo retMap = yunxinT2.getChatroomAddr(params);
        if (retMap != null) {
            result.setYunxin_broadcast_url(retMap.getAddr());
        }
        result.setYunxin_appkey(ConfigValues.getYunxinAppkey());
        result.setAccess_token(AccessTokenUtil.getAccessToken(AccessTokenType.OPENAPI_TOKEN.getVal()));
        /*金币叫法配置*/
        String coinsName = ConfigUtil.getTenantConfig("tenant" + ValueUtil.getString(manager.getTenant_id())).get(
                "tenant.id.coins.name", ConfigValues.COINS_NAME);
        result.setCoin_name(coinsName);
        GoldRegiste(broker);
        return result;
    }
    
    private void GoldRegiste(Broker broker) {
        RegisteForm param = new RegisteForm();
        param.setMobile(broker.getMobile());
        param.setUser_token(GoldTokenUtil.getGoldToken());
        param.setUser_id(broker.getBroker_key());
        param.setTenant_id(String.valueOf(broker.getTenant_id()));
        goldService.goldRegiste(param);
    }
    
    private String saveNewBrokerSession(Long managerId, Broker broker, boolean isManager, LoginFormBackForm result,
            BrokerLoginType loginType) {
        Long client_id = managerId;
        PlatformType type = PlatformType.MANAGE;
        // 根据clientId 获取 客户的 access_token,获取到token 把当前的token 注销掉
        String clientIdToken = com.cloudbroker.bcs.platform.dav.common.util.SessionHelper.getInstance()
                .getSessionTokenByClientId(type, loginType.getVal() + client_id.toString());
        // 客户已经存在token，删除token
        if (!StringUtil.isBlank(clientIdToken)) {
            // 销毁会话令牌
            com.cloudbroker.bcs.platform.dav.common.util.SessionHelper.getInstance().delete(clientIdToken);
        }
        CustomerCache identity = new CustomerCache();
        identity.setClient_id(client_id);
        identity.setBrokerId(broker.getBroker_id());
        if (isManager) {
            //管理员
            Set<String> pers = permissionService.getPermissionsByManagerId(managerId);
            identity.setPermissions(pers);
            identity.setTenantId(broker.getTenant_id());
            identity.setUserType(SysContants.SESSION_USER_TYPE_STAFF);
            StringBuilder sb = new StringBuilder();
            for (String per : pers) {
                sb.append(per);
                sb.append(',');
            }
            if (!pers.isEmpty()) {
                sb.setLength(sb.length() - 1);
            }
            result.setPermissions(sb.toString());
        } else {
            //大V或者粉丝
            identity.setUserType(SysContants.SESSION_USER_TYPE_CLIENT);
        }
        identity.setBroker(broker);
        identity.setBrokerLoginType(loginType.getVal());
        identity.setPlatformType(type.getValue());
        String access_token = com.cloudbroker.bcs.platform.dav.common.util.SessionHelper.getInstance()
                .renewAccess_token(identity);
        
        // 把生成的token保存到缓存
        com.cloudbroker.bcs.platform.dav.common.util.SessionHelper.getInstance().saveNewClientIDSession(type,
                client_id, access_token, broker.getTenant_id(), loginType);
        
        return access_token;
    }
    
    private Broker yunxinReg(Broker c, BrokerManager manager, boolean updateDataBase) {
        // 调用云信接口
        CreateAccountForm param = new CreateAccountForm();
        param.setAccid(c.getBroker_key());
        param.setName(c.getBroker_name());
        param.setIcon(c.getBroker_avatar());
        CreateAccountBackVo yunxinMap = yunxinT2.createAccount(param);
        if (yunxinMap == null) {
            return c;
        }
        String yunxin_token = yunxinMap.getToken();
        manager.setYunxin_token(yunxin_token);
        String yunxin_acct = yunxinMap.getAccid();
        manager.setYunxin_acct(yunxin_acct);
        if (updateDataBase) {
            brokerManagerService.updateCAS(manager);
        }
        return c;
    }
    
    private List<AdpageData> getAdpageDataList(List<AdpageView> adpageList) {
        if (adpageList == null || adpageList.size() == 0) {
            return null;
        }
        List<AdpageData> adpageListData = new ArrayList<AdpageData>();
        for (AdpageView adpage : adpageList) {
            AdpageData adpageData = new AdpageData();
            adpageData.setPage_img(adpage.getPage_img());
            adpageData.setPage_url(adpage.getPage_url());
            adpageListData.add(adpageData);
        }
        return adpageListData;
    }
    
    @Override
    public SuggestionBackList funcSuggestionList(PageVO form) {
        SuggestionBackList result = new SuggestionBackList();
        Integer page_no = ValueUtil.getIntObj(form.getPage_no(), 1);
        Integer page_size = ValueUtil.getIntObj(form.getPage_count(), ConfigValues.getRequestNum());
        Integer total_count = feedbackService.getCount();
        List<SuggestionListView> result_list = feedbackService.getSuggestionList((page_no - 1) * page_size,
                page_size);
        result.setTotal_count(total_count);
        result.newDataList().addAll(result_list);
        return VOUtil.setSuccessResult(result);
    }
    
    @Override
    public UserCountBackForm funcUserCount(UserCountForm form) {
        UserCountBackForm result = new UserCountBackForm();
        int viewpoint_num = 0;
        int question_num = 0;
        int comment_num = 0;
        int upvote_num = 0;
        int live_invest_num = 0;
        Long user_id = Long.valueOf(form.getUser_id());
        int user_type = Integer.parseInt(form.getUser_type());
        if (CustomerType.FANS.getVal() == user_type) {
            Customer c = customerService.getbyUcId(user_id, null);
            if (null == c) {
                return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, UserCountBackForm.class);
            }
            Long customer_id = c.getCustomer_id();
            Integer tenant_id = c.getTenant_id();
            comment_num = viewpointReplyService.countByCustomerId(customer_id, tenant_id);
            question_num = questionService.countByCustomerId(customer_id, tenant_id);
            upvote_num = upvoteWaterService.countByCustomerId(customer_id, tenant_id);
        }
        if (CustomerType.DAV.getVal() == user_type) {
            BrokerManager bm = brokerManagerService.getByUserId(user_id);
            if (null == bm) {
                return VOUtil.genErrorResult(ClientErr.NO_SUCH_CLIENT, UserCountBackForm.class);
            }
            Long broker_id = bm.getBroker_id();
            Integer tenant_id = bm.getTenant_id();
            viewpoint_num = viewpointMsgService.countByBrokerId(broker_id, tenant_id);
            comment_num = viewpointReplyService.countByBrokerId(broker_id, tenant_id);
            upvote_num = upvoteWaterService.countByBrokerId(broker_id, tenant_id);
            live_invest_num = chatTopicService.countByBrokerId(broker_id, tenant_id);
        }
        result.setComment_num(comment_num);
        result.setQuestion_num(question_num);
        result.setLive_invest_num(live_invest_num);
        result.setUpvote_num(upvote_num);
        result.setViewpoint_num(viewpoint_num);
        return VOUtil.setSuccessResult(result);
    }
    
}
